package com.kaifamiao.interceptor;

import com.kaifamiao.token.JsonWebTokenHelper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.logging.Logger;

/**
 * 实现 HandlerInterceptor 接口
 */
public class TokenInterceptor implements HandlerInterceptor {

    private Logger logger;

    private JsonWebTokenHelper tokenHelper;

    public TokenInterceptor(Logger logger, JsonWebTokenHelper tokenHelper) {
        this.logger = logger;
        this.tokenHelper = tokenHelper;
    }

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        logger.info( req.getMethod() + " : " + req.getRequestURI() );
        logger.info( handler.toString() );
        String auth = req.getHeader( "authorization" );
        // 判断 auth 是否为 null 或 为空串
        if( auth == null || auth.trim().isEmpty() ) {
            return false;
        }
        // 判断 auth 是否通过校验
        if( !tokenHelper.verify(auth) ) {
            return false;
        }
        // 获取 payload 中的内容
        Map<String,Object> map = tokenHelper.parseToMap(auth);
        // 将当前已登录用户的 id 设置到 当前请求的属性中
        req.setAttribute( "customerId", map.get( "id" ) );
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView mav) throws Exception {
        logger.info( req.getMethod() + " : " + req.getRequestURI() );
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception ex) throws Exception {
        logger.info( req.getMethod() + " : " + req.getRequestURI() );
    }

}
